<script setup lang="ts">
import { ref } from 'vue'
import { type FormInstance, Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import ClassCalendar from './components/ClassCalendar.vue'
import { useForm } from '@/hooks'
import { ArrangeTemplateApi } from '@/apis/education'

const emit = defineEmits(['ok'])
const selectedList = ref([])

const formRef = ref<FormInstance>()

const visible = ref(false)
const detailId = ref<string>('')
const loading = ref(false)
const isCopy = ref(false)

const { form, resetForm } = useForm({
  name: '',
  fullName: '',
  classYear: '',
  term: '',
  grade: '',
  lessonCount: '',
  // startDate: '',
  // endDate: '',
  lessonList: [],
  daterange: undefined,
})

const rules: FormInstance['rules'] = {
  name: [{ required: true, message: '请输入模板名称' }],
  classYear: [{ required: true, message: '请选择上课年份' }],
  term: [{ required: true, message: '请选择学期' }],
  grade: [{ required: true, message: '请选择年级' }],
  daterange: [{ required: true, message: '请选择开始时间和结束时间' }],
}

const handleOk = () => {
  emit('ok')
}

const beforeOk = async () => {
  const vali = await formRef.value?.validate()
  if (vali) {
    return false
  }
  if (!form.lessonList.length) {
    Message.warning('请选择课次')
    return false
  }
  try {
    const data = JSON.parse(JSON.stringify(form))
    // data.startDate = form.daterange[0]
    // data.endDate = form.daterange[1]
    data.lessonCount = form.lessonList.length
    data.classYear = data.classYear.split('-')[0]
    delete data.daterange
    if (detailId.value && !isCopy.value) {
      await ArrangeTemplateApi.updateArrangeTemplate(data, detailId.value)
      Message.success('编辑成功')
    } else {
      await ArrangeTemplateApi.createArrangeTemplate(data)
      Message.success('添加成功')
    }
    return true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  }
}

watch(selectedList, (val) => {
  form.lessonList = val.map((item: Date, index: number) => ({
    lessonIndex: index + 1,
    lessonDate: dayjs(item).format('YYYY-MM-DD'),
  }))
}, { deep: true })

const reset = () => {
  resetForm()
  selectedList.value = []
  formRef.value?.clearValidate()
}

const handleCancel = () => {
  visible.value = false
}

const getDetail = async (id: string) => {
  try {
    loading.value = true
    const res = await ArrangeTemplateApi.getArrangeTemplateDetail(id)
    form.name = res.name
    form.fullName = res.fullName
    form.classYear = `${res.classYear}01-01`
    form.term = res.term
    form.grade = res.grade
    form.lessonCount = res.lessonCount
    // form.startDate = ''
    // form.endDate = ''
    form.lessonList = res.arrangeLessonList
    form.daterange = [res.startDate, res.endDate]
    selectedList.value = (res.arrangeLessonList || []).map(item => new Date(item.lessonDate))
    loading.value = false
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {}
}

const open = (id?: string, isCp: boolean = false) => {
  reset()
  if (id) {
    detailId.value = id
    getDetail(id)
  } else {
    detailId.value = ''
  }
  isCopy.value = isCp
  visible.value = true
}

defineExpose({ open })
</script>

<template>
  <a-modal v-model:visible="visible" width="960px" :on-before-ok="beforeOk" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      {{ detailId ? '编辑' : '添加' }}模板
    </template>
    <a-spin :loading="loading" style="width: 100%;">
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <div class="content">
          <div class="grid-item">
            <a-form-item label="名称" field="name">
              <a-input v-model.trim="form.name" placeholder="请输入名称" />
            </a-form-item>
          </div>
          <!-- <div class="grid-item-large">
            <a-form-item label="开始时间/结束时间" value-formate="YYYY-M-D" field="daterange">
              <a-range-picker v-model="form.daterange" style="width: 100%;" />
            </a-form-item>
          </div> -->
          <div class="grid-item">
            <a-form-item label="上课年份" field="classYear">
              <a-year-picker v-model="form.classYear" placeholder="请选择上课年份" style="width: 100%;" />
            </a-form-item>
          </div>
          <div class="grid-item">
            <a-form-item label="年级" field="grade">
              <DictSelect v-model="form.grade" code="Grade" placeholder="选择年级" allow-clear />
            </a-form-item>
          </div>
          <div class="grid-item">
            <a-form-item label="学期" field="term">
              <DictSelect v-model="form.term" type="checkbox" code="TermEnum" />
            </a-form-item>
          </div>
        </div>
        <div class="wrap">
          <ClassCalendar v-model="selectedList" />
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<style lang="less" scoped>
.content {
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(2, 1fr);
  column-gap: 30px;

  .grid-item-large {
    grid-column: span 2;
  }
}

.wrap {
  height: 450px;
}
:deep(.arco-radio-checked) {
  background: rgb(var(--primary-6));
  color: #fff;
}
</style>
